package br.com.solutions.delivery.facade.serialization;

import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;

import br.com.solutions.delivery.facade.serialization.intf.ISerializationFacade;


public class SerializationFacade<T> implements ISerializationFacade<T> {
	
	private String nameFile;

	public SerializationFacade(String nameFile){
		this.nameFile = "C:\\" + nameFile;
	}
	
	@Override
	public void saveObjects(List<T> objects) throws FileNotFoundException, IOException{
		File file = null;
		FileOutputStream fileOutputStream = null;
		ObjectOutputStream objectOutputStream = null;
		try {
			file = new File(nameFile);   
			fileOutputStream = new FileOutputStream(file);
			objectOutputStream = new ObjectOutputStream(fileOutputStream);
			objectOutputStream.writeObject(objects);
		} finally {
			close(fileOutputStream);
			close(objectOutputStream);
		}
		
	}
	
	@Override
	@SuppressWarnings("unchecked")
	public List<T> getObjects() throws IOException, ClassNotFoundException{
		 File file = null;
		 FileInputStream fileInputStream = null;
		 ObjectInputStream objectInputStream = null;
		 try {			
			 file = new File(nameFile);
			 fileInputStream = new FileInputStream(file);
			 objectInputStream = new ObjectInputStream(fileInputStream);
			 return  (List<T>) objectInputStream.readObject();
		 } catch (FileNotFoundException e){
			 return new ArrayList<T>();			 
		 } finally {
			 close(fileInputStream);
			 close(objectInputStream);
			 
		 }
	}

	private void close(Closeable closeable) throws IOException {
		if (closeable != null)
			closeable.close();
	}
	
}


